package service

import (
	"context"
	"errors"
	"gitee.com/cristiane/micro-mall-search-users-consumer/model/args"
	"gitee.com/cristiane/micro-mall-search-users-consumer/repository"
	"gitee.com/kelvins-io/common/errcode"
	"gitee.com/kelvins-io/common/json"
	"gitee.com/kelvins-io/kelvins"
)

func NoticeConsume(ctx context.Context, body string) error {
	var err error
	var msg args.CommonBusinessMsg
	err = json.Unmarshal(body, &msg)
	if err != nil {
		return err
	}
	var retCode int
	if msg.Type == args.UserInfoSearchNoticeType {
		var userInfo args.UserInfoSearch
		err = json.Unmarshal(msg.Content, &userInfo)
		if err != nil {
			return err
		}
		// userInfo.Phone == country_code:phone
		retCode = repository.SearchStore(ctx, args.ESIndexUserInfo, userInfo.Phone, msg.Content)
		if retCode == errcode.SUCCESS {
			return nil
		}
		kelvins.BusinessLogger.Errorf(ctx, "userInfo SearchStore err: %v, content: %v", errcode.GetErrMsg(retCode), msg)
		return errors.New(errcode.GetErrMsg(retCode))
	} else if msg.Type == args.MerchantsMaterialInfoNoticeType {
		var merchantInfo args.MerchantInfoSearch
		err = json.Unmarshal(msg.Content, &merchantInfo)
		if err != nil {
			return err
		}
		retCode = repository.SearchStore(ctx, args.ESIndexMerchantsMaterialInfo, merchantInfo.MerchantCode, msg.Content)
		if retCode == errcode.SUCCESS {
			return nil
		}
		kelvins.BusinessLogger.Errorf(ctx, "merchantInfo SearchStore err: %v, content: %v", errcode.GetErrMsg(retCode), msg)
		return errors.New(errcode.GetErrMsg(retCode))
	}

	return err
}

func NoticeConsumeErr(ctx context.Context, err, body string) error {
	return nil
}
